import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../services/api_service.dart';
import '../models/collect.dart';
import '../models/category.dart';
import '../constants/app_constants.dart';

class AddCollectionPage extends StatefulWidget {
  final CollectionItem? editItem;

  const AddCollectionPage({
    super.key,
    this.editItem,
  });

  @override
  State<AddCollectionPage> createState() => _AddCollectionPageState();
}

class _AddCollectionPageState extends State<AddCollectionPage> {
  final _formKey = GlobalKey<FormState>();
  final _titleController = TextEditingController();
  final _contentController = TextEditingController();
  final _discussController = TextEditingController();
  final _sourceController = TextEditingController();
  final _tagController = TextEditingController();
  final List<String> _tags = [];
  bool _isSubmitting = false;

  List<Category> _categories = [];
  bool _isCategoriesLoading = true;
  String? _selectedCategoryId;

  @override
  void initState() {
    super.initState();
    _loadCategories();
    if (widget.editItem != null) {
      // 编辑模式：填充已有数据
      _titleController.text = widget.editItem!.title;
      _contentController.text = widget.editItem!.content;
      _discussController.text = widget.editItem!.discuss;
      _sourceController.text = widget.editItem!.source;
      _tags.addAll(widget.editItem!.tags);
      _selectedCategoryId = widget.editItem!.categoryId.isNotEmpty
          ? widget.editItem!.categoryId
          : null;
    } else {
      // 新增模式：自动读取剪贴板内容
      _loadClipboardContent();
    }
  }

  /// 加载分类列表
  Future<void> _loadCategories() async {
    try {
      final categories = await ApiService.getCategoryList();
      setState(() {
        _categories = categories;
        _isCategoriesLoading = false;
      });
    } catch (e) {
      setState(() {
        _isCategoriesLoading = false;
      });
      print('加载分类列表失败: $e');
    }
  }

  /// 读取剪贴板内容并自动填充到内容输入框
  Future<void> _loadClipboardContent() async {
    try {
      final clipboardData = await Clipboard.getData(Clipboard.kTextPlain);
      if (clipboardData != null && clipboardData.text != null) {
        final clipboardText = clipboardData.text!.trim();
        if (clipboardText.isNotEmpty) {
          setState(() {
            _contentController.text = clipboardText;
          });
          print('自动粘贴剪贴板内容: ${clipboardText.length} 字符');
        }
      }
    } catch (e) {
      print('读取剪贴板失败: $e');
    }
  }

  @override
  void dispose() {
    _titleController.dispose();
    _contentController.dispose();
    _discussController.dispose();
    _sourceController.dispose();
    _tagController.dispose();
    super.dispose();
  }

  bool get isEditMode => widget.editItem != null;

  void _addTag() {
    final tag = _tagController.text.trim();
    if (tag.isNotEmpty && !_tags.contains(tag)) {
      setState(() {
        _tags.add(tag);
        _tagController.clear();
      });
    }
  }

  void _removeTag(String tag) {
    setState(() {
      _tags.remove(tag);
    });
  }

  /// 扁平化分类树，用于下拉选择
  List<Map<String, dynamic>> _flattenCategories(List<Category> categories, {int level = 0}) {
    List<Map<String, dynamic>> result = [];
    for (var category in categories) {
      result.add({
        'id': category.id,
        'name': category.name,
        'level': level,
      });
      if (category.children.isNotEmpty) {
        result.addAll(_flattenCategories(category.children, level: level + 1));
      }
    }
    return result;
  }

  Future<void> _submitForm() async {
    // 先验证基础表单规则
    if (!_formKey.currentState!.validate()) {
      return;
    }

    // 验证标题和内容不能都为空
    if (_titleController.text.trim().isEmpty &&
        _contentController.text.trim().isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('标题和内容不能都为空')),
      );
      return;
    }

    setState(() {
      _isSubmitting = true;
    });

    try {
      if (isEditMode) {
        await ApiService.updateCollection(
          id: widget.editItem!.id,
          title: _titleController.text,
          content: _contentController.text,
          discuss: _discussController.text.trim().isNotEmpty
              ? _discussController.text.trim()
              : null,
          source: _sourceController.text.trim().isNotEmpty
              ? _sourceController.text.trim()
              : null,
          categoryId: _selectedCategoryId,
          tags: _tags.isNotEmpty ? _tags : null,
        );

        if (mounted) {
          Navigator.pop(context, true); // 返回true表示更新成功
        }
      } else {
        await ApiService.createCollection(
          title: _titleController.text,
          content: _contentController.text,
          discuss: _discussController.text.trim().isNotEmpty
              ? _discussController.text.trim()
              : null,
          source: _sourceController.text.trim().isNotEmpty
              ? _sourceController.text.trim()
              : null,
          categoryId: _selectedCategoryId,
          tags: _tags.isNotEmpty ? _tags : null,
        );

        if (mounted) {
          Navigator.pop(context, true); // 返回true表示添加成功
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('${isEditMode ? "更新" : "添加"}失败: $e')),
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isSubmitting = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          isEditMode ? '编辑收藏' : '添加收藏',
          style: const TextStyle(fontSize: AppConstants.appBarTitleFontSize),
        ),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: Form(
        key: _formKey,
        child: ListView(
          padding: const EdgeInsets.all(16),
          children: [
            TextFormField(
              controller: _titleController,
              decoration: const InputDecoration(
                labelText: '标题',
                border: OutlineInputBorder(),
              ),
              enabled: !_isSubmitting,
            ),
            const SizedBox(height: 16),
            // 分类选择下拉框
            DropdownButtonFormField<String>(
              value: _selectedCategoryId,
              decoration: const InputDecoration(
                labelText: '分类',
                border: OutlineInputBorder(),
                hintText: '选择分类（可选）',
              ),
              items: [
                const DropdownMenuItem<String>(
                  value: null,
                  child: Text('未分类'),
                ),
                if (!_isCategoriesLoading)
                  ..._flattenCategories(_categories).map((category) {
                    final level = category['level'] as int;
                    final indent = '  ' * level;
                    return DropdownMenuItem<String>(
                      value: category['id'] as String,
                      child: Text('$indent${category['name']}'),
                    );
                  }).toList(),
              ],
              onChanged: _isSubmitting ? null : (value) {
                setState(() {
                  _selectedCategoryId = value;
                });
              },
              isExpanded: true,
            ),
            const SizedBox(height: 16),
            TextFormField(
              controller: _contentController,
              decoration: const InputDecoration(
                labelText: '内容',
                border: OutlineInputBorder(),
                alignLabelWithHint: true,
              ),
              maxLines: 10,
              enabled: !_isSubmitting,
            ),
            const SizedBox(height: 16),
            TextFormField(
              controller: _discussController,
              decoration: const InputDecoration(
                labelText: '评论',
                border: OutlineInputBorder(),
                alignLabelWithHint: true,
              ),
              maxLines: 5,
              enabled: !_isSubmitting,
            ),
            const SizedBox(height: 16),
            TextFormField(
              controller: _sourceController,
              decoration: const InputDecoration(
                labelText: '出处',
                border: OutlineInputBorder(),
              ),
              enabled: !_isSubmitting,
            ),
            const SizedBox(height: 16),
            Row(
              children: [
                Expanded(
                  child: TextFormField(
                    controller: _tagController,
                    decoration: const InputDecoration(
                      labelText: '标签',
                      border: OutlineInputBorder(),
                      hintText: '输入标签后点击添加',
                    ),
                    enabled: !_isSubmitting,
                    onFieldSubmitted: (_) => _addTag(),
                  ),
                ),
                const SizedBox(width: 8),
                ElevatedButton(
                  onPressed: _isSubmitting ? null : _addTag,
                  child: const Text('添加'),
                ),
              ],
            ),
            if (_tags.isNotEmpty) ...[
              const SizedBox(height: 12),
              Wrap(
                spacing: 8,
                runSpacing: 8,
                children: _tags.map((tag) {
                  return Chip(
                    label: Text(tag),
                    onDeleted: _isSubmitting ? null : () => _removeTag(tag),
                    deleteIcon: const Icon(Icons.close, size: 18),
                  );
                }).toList(),
              ),
            ],
            const SizedBox(height: 24),
            SizedBox(
              height: 48,
              child: ElevatedButton(
                onPressed: _isSubmitting ? null : _submitForm,
                child: _isSubmitting
                    ? const SizedBox(
                        width: 20,
                        height: 20,
                        child: CircularProgressIndicator(strokeWidth: 2),
                      )
                    : const Text('提交'),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
